package com.example.demo_text;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.*;
import java.sql.*;

@WebServlet("/SubmitQuestionServlet")
public class SubmitQuestionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String courseId = request.getParameter("course_id");
        String questionContent = request.getParameter("question_content");

        if (courseId == null || questionContent == null || courseId.trim().isEmpty() || questionContent.trim().isEmpty()) {
            // 提示错误信息
            response.sendRedirect("class_space.jsp?course_id=" + courseId + "&error=课程ID或问题内容不能为空");
            return;
        }

        try {
            Connection conn = UserDAO.getConnection();
            String sql = "INSERT INTO question (course_id, question_content) VALUES (?, ?)";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, courseId);
            stmt.setString(2, questionContent);
            int rowsAffected = stmt.executeUpdate();

            if (rowsAffected > 0) {
                // 插入成功，跳转回 class_space.jsp 并展示 discussion 模块
                // 插入成功后跳转并激活 discussion 标签页
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&tab=discussions");

            } else {
                // 插入失败，提示错误并回到 class_space.jsp
                response.sendRedirect("class_space.jsp?course_id=" + courseId + "&error=问题提交失败，请重试#discussions");
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("class_space.jsp?course_id=" + courseId + "&error=数据库错误：" + e.getMessage() + "#discussions");
        }
    }
}
